package com.bankcomm.ui.views;

import java.util.ArrayList;
import java.util.Map;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.DialogInterface.OnKeyListener;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.KeyEvent;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bankcomm.R;
import com.bankcomm.util.LPUtils;

/**
 * 管理九宫格的添加页面
 * 
 * @author cheng.l 2013-5-10 上午09:43:07
 */
public class LPManageHome implements OnClickListener{

	private Context bv;
	private Dialog popWindow;
	private BCMHomeView homeView;
	private LinearLayout main;
	private Button cancelButton,addButton;
	
	/**
	 * 选中View的集合
	 * */
	private ArrayList<Map<String,Object>> addList = new ArrayList<Map<String,Object>>();
	public LPManageHome(Context context, BCMHomeView homeView) {
		this.bv = context;
		this.homeView = homeView;

		addList.addAll(homeView.mData.array1);
		initPopWindow();
		initGridView();
	}

	private void initPopWindow() {
		// TODO Auto-generated method stub
		View rootView = LayoutInflater.from(bv).inflate(R.layout.layout_grid_manage, null);
		cancelButton = (Button)rootView.findViewById(R.id.cancelManage);
		addButton = (Button)rootView.findViewById(R.id.addManage);
		
		LPUtils.setTitleButtonWH(cancelButton);
		LPUtils.setTitleButtonWH(addButton);
		
		LPUtils.scaledTHeight((LinearLayout)addButton.getParent());
		
		ScrollView scrollView = (ScrollView)rootView.findViewById(R.id.scrollview);
		scrollView.setScrollbarFadingEnabled(false);
		scrollView.setVerticalFadingEdgeEnabled(false);
		
		main = (LinearLayout)rootView.findViewById(R.id.mainview);
		
		popWindow = new Dialog(bv, R.style.dialog);
		popWindow.setContentView(rootView);

		popWindow.setCanceledOnTouchOutside(false);
		Window mWindow = popWindow.getWindow();
		mWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		mWindow.setLayout(ViewGroup.LayoutParams.FILL_PARENT,
				ViewGroup.LayoutParams.FILL_PARENT);
		
		cancelButton.setOnClickListener(this);
		addButton.setOnClickListener(this);
		
		/**
		 * 当对话框关闭时，清空资源
		 */
		popWindow.setOnDismissListener(new OnDismissListener() {
			
			@Override
			public void onDismiss(DialogInterface dialog) {
				// TODO Auto-generated method stub
				realeaseResouces();
			}
		});
		
		/**
		 *监听popwindow的返回按键
		 */
		popWindow.setOnKeyListener(new OnKeyListener() {
			
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				if(keyCode == KeyEvent.KEYCODE_BACK){
					homeView.restoreMyFavorite();
				}
				return false;
			}
		});
	}
	
	/**
	 * 显示popwindow
	 * */
	public void showWindow() {
		if (null != popWindow && !popWindow.isShowing()) {
			popWindow.show();
		}
	}

	/**
	 * 关闭popWindow
	 * */
	public void closeWindow(){
		if(null != popWindow && popWindow.isShowing()){
			popWindow.dismiss();
		}
	}
	
	/**
	 * 创建除"我的首页"以外的GridView
	 * */
	public void initGridView(){
		if(null != homeView.mData.mTitles){
			int length = homeView.mData.mTitles.length;
			for(int i = 1;i < length;i++){
				ArrayList<Map<String, Object>> list = null;
				if(i == 1){
					list = new ArrayList<Map<String,Object>>(homeView.mData.array2);
				}else if(i == 2){
					list = new ArrayList<Map<String,Object>>(homeView.mData.array3);
				}else if(i == 3){
					list = new ArrayList<Map<String,Object>>(homeView.mData.array4);
				}
				
				if(null != addList && addList.size() > 0){
					for(int j = 0 ;j < addList.size();j++){
						Object o = addList.get(j);
						if(list.contains(o)){
							list.remove(o);
						}
					}
				}
				View view = getView(list,homeView.mData.mTitles[i]);
				main.addView(view);
			}			
		}
	}
	
	/**
	 * 得到view含有一个Title和GridView
	 * */
	public View getView(ArrayList<Map<String, Object>> list,String title){
		View view = LayoutInflater.from(bv).inflate(R.layout.layout_city_group_item, null);
		((TextView) view.findViewById(R.id.goupTitle)).setText(title);
		LPCityGridView grid = (LPCityGridView)view.findViewById(R.id.groupGrid);
		grid.drawableHorizontalLine(false);
		grid.setSelector(R.color.transparent);
		grid.setColumns(4);
		grid.setAdapter(new GridAdapter(list));
		
		grid.setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> adapterView, View view, int p,
					long arg3) {
				// TODO Auto-generated method stub
				GridAdapter adapter = (GridAdapter)adapterView.getAdapter();
				@SuppressWarnings("unchecked")
				Map<String,Object> item = (Map<String, Object>) adapter.getItem(p);
				int size = addList.size();
				if(addList.contains(item)){
					addList.remove(item);
				}else{
					addList.add(size-1, item);
				}
				adapter.notifyDataSetChanged();
			}
		});
		return view;
	}
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
		case R.id.cancelManage:
			homeView.restoreMyFavorite();
			closeWindow();
			break;
		case R.id.addManage:
			if(null != addList && addList.size() > 0){
				homeView.updateMyFavorite(addList);
				homeView.uploadToServer(true);
			}else{
				closeWindow();				
			}
			break;
		}
	}
	
	/**
	 * 自定义Adapter
	 * */
	public class GridAdapter extends BaseAdapter{

		private ArrayList<Map<String, Object>> items;
		
		public GridAdapter(ArrayList<Map<String, Object>> items){
			this.items = items;
		}
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return items.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return items.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolder holder = null;
			if(convertView == null){
				convertView = LayoutInflater.from(bv).inflate(R.layout.drop_grid_manage_item, null);
				holder = new ViewHolder();
				holder.name = (TextView)convertView.findViewById(R.id.text_item);
				holder.image = (ImageView)convertView.findViewById(R.id.image_item);
				holder.check = (ImageView)convertView.findViewById(R.id.check);
				
				convertView.setTag(holder);
			}else{
				holder = (ViewHolder)convertView.getTag();
			}
			
			String name = (String) items.get(position).get("name");
			String id = String.valueOf(items.get(position).get("id"));
			
			if(null != name){				
				holder.name.setText(name);
			}

			Bitmap bitmap = DropGridAdapter.getBitmapFromResources(id);
			//---------mode by zhaobin start 判断图片大小并进行缩放-----------
			int width = bitmap.getWidth();
			int localWidth = LPUtils.getCurrentBitmapWidth();
			int localHeight = LPUtils.getCurrentBitmapHeight();
			if (width != localWidth) {
//				float mode = localWidth / width;
				bitmap = LPUtils.createNewBitmap(bitmap, localWidth, localHeight);
			}
            //-----------mode by zhaobin end-------------------
			if (null != bitmap) {
				holder.image.setImageBitmap(bitmap);
			}
			
			if(addList.contains(getItem(position))){
				holder.check.setImageResource(R.drawable.selected);
			}else{
				holder.check.setImageResource(R.drawable.select);
			}
			
			return convertView;
		}
	}
	
	public class ViewHolder{
		TextView name;
		ImageView image;
		ImageView check;
	}
	
	//释放
	public void realeaseResouces(){
		if(null != main){
			main.removeAllViews();
			main = null;
		}
		if(null != addList){
			addList.clear();
			addList = null;					
		}
		
		cancelButton = null;
		addButton = null;
		popWindow = null;
		
		if(null != addList){
			addList.clear();
			addList = null;
		}
	}
}
